//SLIDESHOW

var slideLenght; // lunghezza slider
var boxLength; // lunghezza box contenitore 
var numBoxesSlide; // numero di diapositive
var sommatoreSlide = 0; // sommatore di margine per animazione
var slideSpeed = 700;
var counterFirst = 1; // contatore che mi segnala quando arriva l'ultima diapositiva
var cloneSlide; // clonazione slideshow

function slideLenght(){
	boxLength = $(".content_slide").width();
	numBoxesSlide = $(".content_slide .slide_box").length; // 4 e 3 click
	slideLenght = boxLength*numBoxesSlide;
	$(".slider").css("width",slideLenght);
}

function slideshowRight(){
	if(counterFirst < numBoxesSlide){
		sommatoreSlide = sommatoreSlide+boxLength;
		//alert(sommatoreSlide);
		$(".slider").animate({
			"marginLeft":"-"+sommatoreSlide+"px"
		}, slideSpeed, "swing");
		counterFirst++;
	}else{
		//alert("fine diapositive");
		cloneSlide = $(".content_slide .slider").clone();
		$(".content_slide .slider").after(cloneSlide); // aggiunta copia slider
		$(".content_slide .slider:nth-child(2)").css({
			"marginLeft":boxLength,
			"position":"absolute"
		});
		sommatoreSlide = sommatoreSlide+boxLength;
		$(".content_slide .slider:nth-child(1)").animate({
			"marginLeft":"-"+sommatoreSlide+"px"
		}, slideSpeed, "swing");
		$(".content_slide .slider:nth-child(2)").animate({
			"marginLeft":"0px"
		}, slideSpeed, "swing", function(){
			$(".content_slide .slider:nth-child(1)").remove();
			$(".content_slide .slider").css("position","relative");
		});		
		counterFirst = 1;
		sommatoreSlide = 0;
	};
}

function slideshowLeft(){
	if(counterFirst == 1){
		cloneSlide = $(".content_slide .slider").clone();
		$(".content_slide .slider").before(cloneSlide);
		$(".content_slide .slider:nth-child(1)").css({
			"marginLeft":"-"+slideLenght+"px",
			"position":"absolute"
		});
		$(".content_slide .slider:nth-child(2)").animate({
			"marginLeft":boxLength+"px"
		}, slideSpeed, "swing");
		$(".content_slide .slider:nth-child(1)").animate({
			"marginLeft":"-"+(slideLenght - boxLength)+"px"
		}, slideSpeed, "swing", function(){
			$(".content_slide .slider:nth-child(2)").remove();
			$(".content_slide .slider").css("position","relative");
			counterFirst = numBoxesSlide;
			sommatoreSlide = slideLenght - boxLength;
		});	
	}else{
		sommatoreSlide = sommatoreSlide - boxLength;
		//alert(sommatoreSlide);
		$(".slider").animate({
			"marginLeft":"-"+sommatoreSlide+"px"
		}, slideSpeed, "swing");
		counterFirst--;
	}
}

$(document).ready(function(){
	slideLenght();
	$("#right").live("click", function(){
		slideshowRight();
	});
	$("#left").live("click", function(){
		slideshowLeft();
	});	
	
	$( ".content_slide" ).on( "swipeleft", function(){
		slideshowRight();
	});

	$( ".content_slide" ).on( "swiperight", function(){
		slideshowLeft();
	});
	
});